<template>
    <el-row class="uploadDiv">
        <el-col :span="24">
            <label class="el-form-item__label">{{tableSetJson.label}}</label></el-col>
        <el-col :span="24">
            <el-upload
                    :action="fileUrl"
                    :disabled="imgDisplay"
                    :data="fileUploadData"
                    :headers="headers"
                    ref="listload"
                    list-type="picture-card"
                    :file-list="fileList"
                    :on-success="uploadSuccess"
                    :before-upload="beforeUpload"
                    :auto-upload="true"
                    multiple>
                <i class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                    <img :src="file.pngUrl"
                         class="aligncenter" height="60" width="60"
                         alt="">
                    <div style="position:absolute; bottom:0;">{{file.name}}</div>
                    <span class="el-upload-list__item-actions">
                        <span
                                class="el-upload-list__item-preview"
                                @click="handlePictureCardPreview(file)"
                        >
                        <i class="el-icon-zoom-in"></i>
                        </span>
                        <span
                                v-if="!imgDisplay"
                                class="el-upload-list__item-delete"
                                @click="handleDownload(file)"
                        >
                        <i class="el-icon-download"></i>
                        </span>
                        <span
                                v-if="!imgDisplay"
                                class="el-upload-list__item-delete"
                                @click="handleRemove(file)"
                        >
                        <i class="el-icon-delete"></i>
                        </span>
                </span>
                </div>
            </el-upload>
        </el-col>
    </el-row>
</template>

<script>
    import {uploadFile_Url, deleteFileUrl, executionSql, showPictureByidUrl} from "@/config/api"
    import qs from 'qs'
    import {constants} from 'crypto';

    export default {
        name: "imgupload",
        props: {
            /* 父组件传过来的数据 */
            tableSetJson: {
                type: Object
            },
            raid: {
                type: String
            },
            linkTableType: {
                type: String
            }
        },
        data() {
            return {
                fileList: [],
                fileUrl: '',//上传地址
                fileUploadData: {
                    raid: "",
                    linkTableType: "",
                    rnucode: "",
                    project: "",
                    fileName: ""
                },//上传参数
                imgDisplay: false,
                dialogVisible: false,
                raId: this.raid,
                mulrenum: {},
                filetemp: [],
                token: ""
            };
        },
        created() {
            console.log("---> sms no: ", JSON.stringify(this.raid));
            this.token = localStorage.getItem("set_token");

            if (this.tableSetJson.display != null && this.tableSetJson.display != undefined) {
                this.imgDisplay = this.tableSetJson.display;
            }
            this.comUploadParam();
            this.queryUploadFile();
        },
        watch: {
            raid(val) {
                console.log("---> watch raid: ", val);
                this.raId = val;
                this.comUploadParam();
            }
        },
        computed: {
            headers() {
                return {
                    "Authorization": this.token // 直接从本地获取token就行
                }
            }
        },
        methods: {
            //初始化上传参数
            comUploadParam() {
                this.fileUrl = this.axios.defaults.baseURL + "/quality/common/multifilesUpload";
                this.fileUploadData = {
                    raid: this.raId,
                    linkTableType: this.linkTableType,
                    rnucode: this.tableSetJson.name,
                    project: localStorage.getItem("project_id"),
                    fileName: ""
                }
            },
            uploadSuccess(response, file, fileList) {
                if (response.success === true) {
                    this.$message.success('上传成功！');
                    this.comUploadParam();
                    this.queryUploadFile();
                } else {
                    this.$message.error('上传失败！')
                }
            },
            setPlaceholder() {
                return this.tableSetJson.texttip;
            },
            handleRemove(file) {
                deleteFileUrl({
                    docId: file.docId
                }).then(res => {
                    if (res.data.success === true) {
                        this.$message.success('删除成功！');
                        this.queryUploadFile();
                    } else {
                        this.$message.error('删除失败：' + res.data.msg);
                    }
                });
            },
            handlePictureCardPreview(file) {
                var fileName = file.docId + "." + file.ext;
                let url = sessionStorage.getItem("base_url") + "/common/showFileToPDF?fileName=" + fileName + "";
                window.open(
                    url,
                    "_blank"
                );
            },
            handleDownload(file) {
                const data = {docId: file.docId};
                this.axios.post("/quality/common/downFile", qs.stringify(data), {
                    responseType: "blob"
                }).then(data => {
                    if (data.status === 200) {
                        const blob = new Blob([data.data]);
                        const url = window.URL.createObjectURL(blob);
                        const downloadElement = document.createElement("a");
                        downloadElement.href = url;
                        downloadElement.download = file.name;
                        document.body.appendChild(downloadElement);
                        downloadElement.click();
                        document.body.removeChild(downloadElement);
                        window.URL.revokeObjectURL(blob);
                    }
                });
            },
            queryUploadFile() {
                this.fileList = [];
                if (this.raId != null && this.raId != "") {

                    executionSql({
                        dsCode: "SECURITY_UPLOAD_FILESBYCODE",
                        smsNo: this.raId,
                        rnucode: this.tableSetJson.name
                    }).then(res => {
                        if (res.data.success === true) {
                            for (var index = 0; index < res.data.data.length; index++) {
                                var tempFile = {
                                    docId: "",
                                    name: "",
                                    ext: "",
                                    url: "",
                                    pngUrl: ""
                                }
                                tempFile.docId = res.data.data[index].DOC_ID;
                                tempFile.name = res.data.data[index].DOC_NAME;
                                tempFile.ext = res.data.data[index].DOC_EXT;
                                if (tempFile.ext.toLowerCase() == "pdf") {
                                    tempFile.pngUrl = ""
                                } else if (tempFile.ext.toLowerCase() == "doc" || tempFile.ext.toLowerCase() == "docx") {
                                    tempFile.pngUrl = ""
                                } else if (tempFile.ext.toLowerCase() == "xls" || tempFile.ext.toLowerCase() == "xlsx") {
                                    tempFile.pngUrl = ""
                                } else if (tempFile.ext.toLowerCase() == "ppt" || tempFile.ext.toLowerCase() == "pptx") {
                                    tempFile.pngUrl = ""
                                } else if (tempFile.ext.toLowerCase() == "rar" || tempFile.ext.toLowerCase() == "zip") {
                                    tempFile.pngUrl = ""
                                } else if (tempFile.ext.toLowerCase() == "png" || tempFile.ext.toLowerCase() == "jpg" || tempFile.ext.toLowerCase() == "jepg") {
                                    tempFile.pngUrl = ""
                                } else {
                                    tempFile.pngUrl = ""
                                }
                                this.fileList.push(tempFile);
                                console.log("--> file list: ", JSON.stringify(this.fileList));
                            }
                        }

                    });
                } else {
                    this.fileList = [];
                }
            },
            beforeUpload(file) {
                if (this.raId == null || this.raId === "") {
                    this.raId = this.raid;
                    this.comUploadParam();
                    if (this.raId == null || this.raId === "") {
                        this.$message.error('未生成填报，不允许上传！');
                        return false;
                    }
                }
                this.globalNo = this.raId;
                let orgfileName = file.name;
                this.fileUploadData.fileName = orgfileName;
            }
        }
    };
</script>

<style>
    .uploadDiv {
        margin-left: 10px;
        margin-right: 10px;
    }

    .aligncenter {
        clear: both;
        display: block;
        margin: auto;
        position: absolute;
        top: 40%;
        left: 50%;
        transform: translate(-40%, -50%);
    }
</style>